﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Controls;
using System.Collections;

namespace MyMusicCollection.Model
{
	class SearchHandler
	{
		public List<SearchResult> DoSearch(string aQuery, string aType)
		{
			List<SearchResult> searchResult = new List<SearchResult>();

			Model.DiscogsReader dcReader = new Model.DiscogsReader();
			XmlTextReader xmlReader = dcReader.GetSearchResponse(aQuery, aType);
			XmlDocument xmlDoc = new XmlDocument();

			if (xmlReader == null)
			{
				Console.WriteLine("Fel vid kopplingen till Discogs.");
				return null;
			}

			try
			{
				xmlReader.Read();
				xmlDoc.LoadXml(xmlReader.ReadOuterXml());
				xmlReader.Close();

				int onlyFirst = 0;

				XmlNodeList nList = xmlDoc.SelectNodes("resp/exactresults/result");

				foreach (XmlNode node in nList)
				{
					onlyFirst++;

					if (onlyFirst == 1)
					{
						SearchResult newResult = new SearchResult();

						newResult.mName = node.SelectSingleNode("title").InnerText;

						newResult.mUri = node.SelectSingleNode("uri").InnerText;

						searchResult.Add(newResult);
					}
				}

				return searchResult;
			}
			catch (Exception e)
			{
				Console.WriteLine("Något gick fel med kopplingen till Discogs.");
				xmlReader.Close();
				return null;
			}
		}
	}
}
